/*!
 @header ConsigneeListViewController.m
 @author 王 文彬
 @version 1.0.0 2013/01/30 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "ConsigneeListViewController.h"
#import "Helper.h"
#import "Config.h"
#import "ConsigneeFormViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "JMFBase.h"
#import "RTLabel.h"


//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：ConsigneeListViewController功能较为简单，以tableview的形式显示出地址列表即可。同时还要标记出默认地址，如果用户有设置过的话。
//
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>

@interface ConsigneeListViewController ()

@end

@implementation ConsigneeListViewController
@synthesize dataSource = _dataSource;
@synthesize tableView = _tableView;
@synthesize addButton = _addButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = _L(@"vc_title_011");     //地址管理
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, _SYS_FRAME_HEIGHT-88.0f) style:UITableViewStyleGrouped];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    
    //背景
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    _tableView.backgroundColor = _SYS_COLOR_BACKGROUND;
    _tableView.backgroundView = nil;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    //导航栏左按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    _dataSource = [[NSMutableArray alloc] init];
    
    _addButton = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, _SYS_FRAME_HEIGHT-84.0f-5.0f, 300.0f, 40.0f)];
    _addButton.titleLabel.font = _SYS_FONT_009;
    [_addButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_btn_006_n@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_addButton setTitle:_L(@"vc_title_009") forState:UIControlStateNormal];
    [_addButton addTarget:self action:@selector(addButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_addButton];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CONSIGNEE_LIST];
    request.delegate = self;
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    [request asynchronous];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
      
        cell.textLabel.font = _SYS_FONT_003;
        cell.textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        cell.detailTextLabel.font = _SYS_FONT_001;
        cell.detailTextLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        
        UILabel *defaultLabel = [[UILabel alloc] initWithFrame:CGRectNull];
        defaultLabel.backgroundColor = [UIColor clearColor];
        defaultLabel.textColor = [UIColor colorWithRed:171/255.0f green:171/255.0f blue:171/255.0f alpha:1.0f];
        defaultLabel.font = _SYS_FONT_002;
        [cell.contentView addSubview:defaultLabel];
        
    }
    
    NSDictionary* consignee = [_dataSource objectAtIndex:indexPath.section];

    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", [consignee objectForKey:@"consignee"], [consignee objectForKey:@"region"]];
    
    if ([[consignee objectForKey:@"status"] boolValue]) {
        
        CGSize size = [cell.textLabel.text sizeWithFont:_SYS_FONT_006];
        
        ((UILabel *)[cell.contentView subviews][2]).frame = CGRectMake(size.width+5.0f, 7.0f, 100.0f,size.height);
        ((UILabel *)[cell.contentView subviews][2]).text = [NSString stringWithFormat:@"(%@)",_L(@"title_90")];
    }
    else {
        ((UILabel *)[cell.contentView subviews][2]).text = @"";
    }
    
    cell.detailTextLabel.text = consignee[@"address"];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    ConsigneeFormViewController* consigneeFormViewController = [[ConsigneeFormViewController alloc] initWithConsignee:[_dataSource objectAtIndex:indexPath.section]];
    
    [self.navigationController pushViewController:consigneeFormViewController animated:true];
}

#pragma mark - 私有方法

- (void)setViewNeedDisplay:(BOOL)managing
{
    if (managing) {
        
        [UIView animateWithDuration:0.5f animations:^{
            _addButton.alpha = 1.0f;
            _tableView.frame = CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-88.0f);
            
            if (_dataSource.count == 0) {
                _blankPage.frame = CGRectMake(0.0f, -44.0f, 320.0f, _SYS_FRAME_HEIGHT-44.0f);
            }
        }];
        
    }
    else {
        
        [UIView animateWithDuration:0.5f animations:^{
            _addButton.alpha = 0.0f;
            _tableView.frame = CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT);
            
            if (_dataSource.count == 0) {
                _blankPage.frame = CGRectMake(0.0f, -44.0f, 320.0f, _SYS_FRAME_HEIGHT);
            }
        }];
    }
}

/*!
 @abstract 通过数据源是否为空来判断页面的显示
 */
- (void)viewNeedsDisplay
{
    if (_dataSource.count == 0) {
        
        _blankPage = [[UIView alloc] initWithFrame:CGRectMake(0.0f, -44.0f, 320.0f, _SYS_FRAME_HEIGHT-44.0f)];
        _blankPage.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 139/2.0f, 137.0f/2.0f)];
        imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_013@2x" ofType:@"png"]];
        imageView.center = _blankPage.center;
        [_blankPage addSubview:imageView];
        

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, imageView.frame.origin.y+imageView.frame.size.height+10.0f, 300.0f, 50.0f)];
        label.textAlignment = UITextAlignmentCenter;
        label.numberOfLines = 0;
        label.textColor = [UIColor grayColor];
        label.text = _L(@"alert_104");
        [_blankPage addSubview:label];
        
        [self.view addSubview:_blankPage];
        
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.view.backgroundColor = [UIColor whiteColor];
    }else{

        [_blankPage removeFromSuperview];
        self.tableView.backgroundColor = _SYS_COLOR_BACKGROUND;
        self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    }
}


#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent
{
    [self.navigationController popViewControllerAnimated:true];
}

- (void)addButtonEvent
{
    ConsigneeFormViewController* consigneeFormViewController = [[ConsigneeFormViewController alloc] initWithConsignee:nil];
    
    UINavigationController* consigneeFormNavigationController = [[UINavigationController alloc] initWithRootViewController:consigneeFormViewController];
    [Helper navigationControllerCommonStyle:consigneeFormNavigationController];
    
    [self.navigationController presentModalViewController:consigneeFormNavigationController animated:true];

}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        if (_dataSource == nil) {
            _dataSource = [[NSMutableArray alloc] init];
        }
        else {
            [_dataSource removeAllObjects];
        }
        
        [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
        
        [_tableView reloadData];
    }
    else if (jmf.status == JMStatusInvald) {
        
        [_dataSource removeAllObjects];
        [_tableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
    [self viewNeedsDisplay];
    
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

@end
